/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v2.uid.UidUtils;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.business.domain.PricServiceItem;
import me.zhengjie.business.service.PricServiceItemService;
import me.zhengjie.business.service.dto.PricServiceItemQueryCriteria;
import me.zhengjie.business.util.HttpNewMicProvince;
import me.zhengjie.business.util.SmUtilProvince;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.nmi.ChsInterfaceConfig;
import me.zhengjie.nmi.ChsUtil;
import me.zhengjie.utils.DateTimeUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author xiahongbo
* @date 2024-12-27
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "护理机构服务项目管理")
@RequestMapping("/api/pricServiceItem")
public class PricServiceItemController {

    private final PricServiceItemService pricServiceItemService;

    private final DeptService deptService;

    private final HttpNewMicProvince httpNewMicProvince;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('pricServiceItem:list')")
    public void exportPricServiceItem(HttpServletResponse response, PricServiceItemQueryCriteria criteria) throws IOException {
        pricServiceItemService.download(pricServiceItemService.queryAll(criteria), response);
    }

    @GetMapping(value = "/queryPricServiceItem8106")
    @ApiOperation("查询护理机构服务项目")
    public ResponseEntity<Object> queryPricServiceItem8106(PricServiceItemQueryCriteria criteria) {

        String bcn = DateUtil.now() + (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);

        String input = "{\"data\": {" +
                "\"longterm_servitem_no\":\"\"," +
                "\"longterm_servitem_name\": \""+criteria.getLongtermServitemName()+"\"," +
                "\"loc_admdvs\": \"229900\"," +
                "\"longterm_serv_type\": \""+criteria.getLongtermServType()+"\"}}";
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8101\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "查询服务项目", deptDto);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);


            JSONArray itemArray = JSONArray.parseArray(decryptionResult);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("content", itemArray);
            map.put("totalElements", itemArray.size());
            return new ResponseEntity<>(map, HttpStatus.OK);
        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }

    }

    @GetMapping
    @Log("查询护理机构服务项目")
    @ApiOperation("查询护理机构服务项目")
    @PreAuthorize("@el.check('pricServiceItem:list')")
    public ResponseEntity<Object> queryPricServiceItem(PricServiceItemQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(pricServiceItemService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增护理机构服务项目")
    @ApiOperation("新增护理机构服务项目")
    @PreAuthorize("@el.check('pricServiceItem:add')")
    public ResponseEntity<Object> createPricServiceItem(@Validated @RequestBody PricServiceItem resources){

        String bcn = DateUtil.now() + (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        String datetime = DateTimeUtil.getDateTime();

        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        String no = resources.getNursOrgServitemNo();
        String id = username + "-" + no;

        resources.setLongtermOrgServitemEvtId(id);
        resources.setLongtermOrgServitemId(id);
        resources.setNurscareOrgId(deptDto.getOrgId());
        resources.setNurscareOrgNo(deptDto.getDeptCode());
        resources.setNurscareOrgName(deptDto.getDeptName());
        // 启用
        resources.setEnabStas("1");
        // 审核状态
        resources.setChkStas("2");
        // 事件类型
        resources.setEvtType("01");
        resources.setRid(IdUtil.simpleUUID());
        resources.setCrteTime(DateTimeUtil.getNow());
        resources.setUpdtTime(DateTimeUtil.getNow());
        resources.setCrterId(String.valueOf(userId));
        resources.setCrterName(nickName);
        resources.setCrteOptinsNo(deptDto.getDeptCode());

        resources.setOpterId(String.valueOf(userId));
        resources.setOpterName(nickName);
        resources.setOptinsNo(deptDto.getDeptCode());
        resources.setOptTime(DateTimeUtil.getNow());
        // 有效标志
        resources.setValiFlag("1");
        return new ResponseEntity<>(pricServiceItemService.create(resources),HttpStatus.CREATED);
/*

        String input = "{\"data\": {" +
                "\"longterm_org_servitem_evt_id\":\""+resources.getLongtermOrgServitemEvtId()+"\"," +
                "\"longterm_org_servitem_id\": \""+resources.getLongtermOrgServitemId()+"\"," +
                "\"nurscare_org_name\": \""+resources.getNurscareOrgName()+"\"," +
                "\"nurscare_org_id\": \""+resources.getNurscareOrgId()+"\"," +
                "\"nurscare_org_no\": \""+resources.getNurscareOrgNo()+"\"," +
                "\"longterm_servitem_id\": \""+resources.getLongtermServitemId()+"\"," +
                "\"longterm_servitem_no\": \""+resources.getLongtermServitemNo()+"\"," +
                "\"longterm_servitem_name\": \""+resources.getLongtermServitemName()+"\"," +
                "\"longterm_serv_type\": \""+resources.getLongtermServType()+"\"," +
                "\"selfpay_prop\": \""+resources.getSelfpayProp()+"\"," +
                "\"pric_uplmt\": \""+resources.getPricUplmt()+"\"," +
                "\"adv_dura_uplmt\": \""+resources.getAdvDuraUplmt()+"\"," +
                "\"nurscare_org_servitem_no\": \""+resources.getNursOrgServitemNo()+"\"," +
                "\"nurscare_org_servitem_name\": \""+resources.getNursOrgServitemName()+"\"," +
                "\"nurscare_org_servitem_type\": \""+resources.getNursOrgServitemType()+"\"," +
                "\"nurscare_org_admdvs\": \""+resources.getNursOrgAdmdvs()+"\"," +
                "\"nurscare_org_servitem_pric\": \""+resources.getNursOrgServitemPric()+"\"," +
                "\"nurscare_org_servitem_prcunt_no\": \""+resources.getNursOrgServitemPrcuntNo()+"\"," +
                "\"nurscare_org_servitem_memo\": \""+resources.getNursOrgServitemMemo()+"\"," +
                "\"enab_stas\": \""+resources.getEnabStas()+"\"," +
                "\"chk_stas\": \""+resources.getChkStas()+"\"," +
                "\"oprt_opnn\": \"\"," +
                "\"rchk_opnn\": \"\"," +
                "\"serv_matt_inst_id\": \"\"," +
                "\"serv_matt_node_inst_id\": \"\"," +
                "\"evt_inst_id\": \"\"," +
                "\"evt_type\": \""+resources.getEvtType()+"\"," +
                "\"rid\": \""+resources.getRid()+"\"," +
                "\"crte_time\": \""+datetime+"\"," +
                "\"updt_time\": \""+datetime+"\"," +
                "\"crter_id\": \""+resources.getCrterId()+"\"," +
                "\"crter_name\": \""+resources.getCrterName()+"\"," +
                "\"crte_optins_no\": \""+resources.getCrteOptinsNo()+"\"," +
                "\"opter_id\": \""+resources.getOpterId()+"\"," +
                "\"opter_name\": \""+resources.getOpterName()+"\"," +
                "\"opt_time\": \""+datetime+"\"," +
                "\"optins_no\": \""+resources.getOptinsNo()+"\"," +
                "\"admdvs\": \""+resources.getAdmdvs()+"\"," +
                "\"vali_flag\": \""+resources.getValiFlag()+"\"," +
                "\"data_ver\": \"\"," +
                "\"opt_dot_id\": \"\"," +
                "\"LongtermOrgServitemAttDTO\": \"\"," +
                "\"asst_prdr\": \"\"," +
                "\"asst_avl_cnt\": \"\"," +
                "\"asst_spec\": \"\"," +
                "\"asst_type\": \"\"," +
                "\"asst_prod_type\": \"\"," +
                "\"centre_asst_type\": \"\"," +
                "\"centre_asst_prod_type\": \"\"}}";
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8106\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "新增服务项目", deptDto);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);

        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }
*/

    }

    @PutMapping
    @Log("修改护理机构服务项目")
    @ApiOperation("修改护理机构服务项目")
    @PreAuthorize("@el.check('pricServiceItem:edit')")
    public ResponseEntity<Object> updatePricServiceItem(@Validated @RequestBody PricServiceItem resources){
        pricServiceItemService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除护理机构服务项目")
    @ApiOperation("删除护理机构服务项目")
    @PreAuthorize("@el.check('pricServiceItem:del')")
    public ResponseEntity<Object> deletePricServiceItem(@RequestBody String[] ids) {
        pricServiceItemService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}